<?php
namespace EasySwoole\EasySwoole;

use EasySwoole\EasySwoole\Swoole\EventRegister;
use EasySwoole\EasySwoole\AbstractInterface\Event;
use EasySwoole\Http\Request;
use EasySwoole\Http\Response;
use EasySwoole\ORM\DbManager;
use EasySwoole\ORM\Db\Connection;
use EasySwoole\ORM\Db\Config;
use EasySwoole\EasySwoole\Crontab\Crontab;
use App\HttpController\Index\TaskOne;


class EasySwooleEvent implements Event
{

    public static function initialize()
    {
        // TODO: Implement initialize() method.
        date_default_timezone_set('Asia/Shanghai');
    }

    public static function mainServerCreate(EventRegister $register)
    {
        // TODO: Implement mainServerCreate() method.
        	   
		$instance = \EasySwoole\EasySwoole\Config::getInstance();
		$mysql = $instance->getConf('MYSQL');
		
        $config = new Config();
	    $config->setDatabase($mysql['database']);
	    $config->setUser($mysql['user']);
	    $config->setPassword($mysql['password']);
	    $config->setHost($mysql['host']);
	
	    DbManager::getInstance()->addConnection(new Connection($config));

        // 开始一个定时任务计划 
        Crontab::getInstance()->addTask(TaskOne::class);
    }

    public static function onRequest(Request $request, Response $response): bool
    {
        // TODO: Implement onRequest() method.
	    $response->withHeader('Access-Control-Allow-Origin', '*');
	    $response->withHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
	    $response->withHeader('Access-Control-Allow-Credentials', 'true');
	    $response->withHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
	    if ($request->getMethod() === 'OPTIONS') {
	        $response->withStatus(Status::CODE_OK);
	        return false;
	    }
	    return true;
   
    }

    public static function afterRequest(Request $request, Response $response): void
    {
        // TODO: Implement afterAction() method.
    }
}